﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using LView.CMS.IServices;
using LView.CMS.Core;
using LView.CMS.Models;
using LView.CMS.ViewModels;
using LView.CMS.Core.Helper;
using Aspose.Slides;
using System.Drawing;
using System.Drawing.Imaging;
using LView.CMS.ViewModels.MyTask;
using ce.office.extension;
using System.IO;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.Util;
using System.Web;

namespace LView.CMS.Site.Controllers
{
    public class MyTaskController : BaseController
    {
        private readonly IMyTaskService _myTaskService;
        public MyTaskController(IMyTaskService myTaskService)
        {
            _myTaskService = myTaskService;
        }
        public IActionResult Index()
        {
            var (myTaskList, myTaskCount) = _myTaskService.GetMyTaskList(CurrentUser.UserId);
            return View(myTaskList);
        }

        public IActionResult TimeLine()
        {
            var (myTaskList, myTaskCount) = _myTaskService.GetMyTaskList(CurrentUser.UserId);
            return View(myTaskList);
        }

        public IActionResult MyTaskDetail(string taskId, string courseId)
        {
            var taskInfo = MongodbHelper.Instance.FindEntity<LTask>(x => x.Id == taskId);
            var (processInfo, processCount) = MongodbHelper.Instance.FindList<LProcess>(x => x.TaskId == taskId && x.UserId == CurrentUser.UserId);
            var hasStudyPeriod = 0; var hasGotScore = 0;
            processInfo.ForEach(x => { hasStudyPeriod += x.CourseGotPeriod; hasGotScore += x.CourseGotScore; });
            ViewData["hasStudyPeriod"] = hasStudyPeriod;
            ViewData["hasGotScore"] = hasGotScore;
            return View(taskInfo);
        }

        public async Task<IActionResult> ShowOtherDetailAsync(string courseFileId, string courseId, string taskId, string courseRequiredTime)
        {
            if (courseFileId != null)
            {
                var courseFile = MongodbHelper.Instance.FindEntity<LFile>(x => x.Id == courseFileId);
                var coursePath = courseFile.Path;
                ViewData["RemainTime"] = await _myTaskService.GetRemainTime(taskId, courseId, User.Claims.FirstOrDefault(x => x.Type == "ID").Value);
                var file = new FileInfo(coursePath);

                #region pptx/pdf
                if (courseFile.Name.Contains(".pptx") || courseFile.Name.Contains(".pdf"))
                {
                    ViewData["fileType"] = "ppt";
                    var dir = file.Directory;
                    var filenameArr = file.Name.Split('.');
                    var picList = new List<string>();
                    if (courseFile.Name.Contains(".pptx"))
                    {
                        using (Presentation pres = new Presentation(coursePath))
                        {
                            var w = (int)pres.SlideSize.Size.Width;
                            var h = (int)pres.SlideSize.Size.Height;
                            foreach (ISlide sld in pres.Slides)
                            {
                                Bitmap bmp = sld.GetThumbnail(new Size(w, h));
                                var index = sld.SlideNumber;
                                Console.WriteLine(index);
                                var f = dir + "\\" + $"{filenameArr[0]}_{index}.png";
                                var serverFile = $"http://10.32.36.174:8099/LView.CMS.Assets/" + $"{courseFile.Type}/{filenameArr[0]}_{index}.png";
                                picList.Add(serverFile);
                                System.IO.File.Delete(f);
                                bmp.Save(f, ImageFormat.Png);
                            }
                        }
                    }
                    if (courseFile.Name.Contains(".pdf"))
                    {
                        Aspose.Pdf.Document doc = new Aspose.Pdf.Document(@"zzzzzz.pdf");
                        if (doc == null)
                            throw new Exception("pdf文件无效或者pdf文件被加密！");
                        var startPageNum = 1; var endPageNum = doc.Pages.Count;
                        for (int i = startPageNum; i <= endPageNum; i++)
                        {
                            MemoryStream stream = new MemoryStream();
                            var f = dir + "\\" + $"{filenameArr[0]}_{i}.png";
                            var serverFile = $"http://10.32.36.174:8099/LView.CMS.Assets/" + $"{courseFile.Type}/{filenameArr[0]}_{i}.png";
                            picList.Add(serverFile);
                            Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(128);
                            Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100);
                            jpegDevice.Process(doc.Pages[i], stream);
                            Image img = Image.FromStream(stream);
                            Bitmap bm = new Bitmap(img);
                            bm.Save(f, ImageFormat.Png);
                            img.Dispose();
                            stream.Dispose();
                            bm.Dispose();
                        }
                    }

                    ViewData["PicList"] = picList;
                }
                #endregion

                #region xlsx
                if (courseFile.Name.Contains(".xlsx"))
                {
                    ViewData["fileType"] = "xlsx";
                    var (contentHtmlStr, styleHtmlStr) = Core.Helper.ExcelHelper.ToHtml(file.FullName);
                    ViewData["ContentHtmlStr"] = HttpUtility.HtmlDecode(contentHtmlStr);
                    ViewData["StyleHtmlStr"] = HttpUtility.HtmlDecode(styleHtmlStr);
                }
                #endregion

                #region docx
                if (courseFile.Name.Contains(".docx"))
                {
                    ViewData["fileType"] = "docx";
                    var htmlStr = WordHelper.ToHtml(file.FullName);
                    ViewData["StyleHtmlStr"] = HttpUtility.HtmlDecode(htmlStr.Substring(htmlStr.IndexOf("<style>"), htmlStr.IndexOf("</style>") - htmlStr.IndexOf("<style>")) + "</style>");
                    ViewData["ContentHtmlStr"] = HttpUtility.HtmlDecode(htmlStr.Substring(htmlStr.IndexOf("<body>"), htmlStr.IndexOf("</body>") - htmlStr.IndexOf("<body>")).Replace("<body>", ""));
                }
                #endregion
            }
            return View();
        }

        public async Task<IActionResult> ShowVideoDetail(string courseFileId, string courseId, string taskId, string courseRequiredTime)
        {
            if (courseFileId != null)
            {
                var courseFile = MongodbHelper.Instance.FindEntity<LFile>(x => x.Id == courseFileId);
                var coursePath = $"http://10.32.36.174:8099/LView.CMS.Assets/" + $"{courseFile.Type}/{courseFile.Name}";
                ViewData["RemainTime"] = await _myTaskService.GetRemainTime(taskId, courseId, User.Claims.FirstOrDefault(x => x.Type == "ID").Value);
                ViewData["VideoUrl"] = coursePath;
            }
            return View();
        }

        public IActionResult ShowExamPageDetail(string courseExamId, string courseId, string taskId)
        {
            var exam = MongodbHelper.Instance.FindEntity<LExam>(x => x.Id == courseExamId);
            ViewData["courseId"] = courseId;
            ViewData["taskId"] = taskId;
            return View(exam);
        }

        public async Task<string> UpdateProcess(string TaskId, string CourseId, decimal timeOfThisTimes)
        {
            var result = new BaseResult();
            result = await _myTaskService.SaveLProcess(new LProcess
            {
                Id = Guid.NewGuid().ToString(),
                UserId = CurrentUser.UserId,
                TaskId = TaskId,
                CourseId = CourseId
            }, timeOfThisTimes);
            return JsonHelper.ObjectToJSON(result);
        }

        [HttpPost]
        [Route("/MyTask/SubmitAnswer")]
        public string SubmitAnswer(string examId, string TaskId, string CourseId, List<MyExamAnswer> answerInfoDetails)
        {
            var result = new BaseResult();
            var process = new LProcess
            {
                Id = Guid.NewGuid().ToString(),
                UserId = CurrentUser.UserId,
                TaskId = TaskId,
                CourseId = CourseId
            };
            result = _myTaskService.SaveExamProcess(examId, process, answerInfoDetails);
            return JsonHelper.ObjectToJSON(result);
        }
    }
}
